using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

public class EventListener
{
    public GameObject listeningObject;
}

public static class GeEvent
{
    private static Dictionary<string, Delegate> events = new Dictionary<string, Delegate>();
    private static List<EventListener> listeners = new List<EventListener>();

    // 监听事件
    public static void On(string eventName, Delegate handler, GameObject listeningObject)
    {
        if (!events.ContainsKey(eventName))
        {
            events[eventName] = null;
        }
        EventListener newListener = new EventListener { listeningObject = listeningObject };
        listeners.Add(newListener);
        events[eventName] = Delegate.Combine(events[eventName], handler);
    }

    // 发送事件
    public static void Send(string eventName, params object[] parameters)
    {
        if (events.ContainsKey(eventName))
        {
            Delegate del = events[eventName];
            if (del != null)
            {
                var invocationList = del.GetInvocationList();
                foreach (Delegate handler in invocationList)
                {
                    ParameterInfo[] handlerParameters = handler.Method.GetParameters();
                    if (handlerParameters.Length == parameters.Length)
                    {
                        bool parameterMatch = true;
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            if (handlerParameters[i].ParameterType != parameters[i].GetType())
                            {
                                parameterMatch = false;
                                break;
                            }
                        }
                        if (parameterMatch)
                        {
                            handler.DynamicInvoke(parameters);
                        }
                    }
                }
            }
        }
    }

    // 删除事件
    public static void Off(string eventName, Delegate handler, GameObject listeningObject)
    {
        if (events.ContainsKey(eventName))
        {
            events[eventName] = Delegate.Remove(events[eventName], handler);
            if (events[eventName] == null)
            {
                events.Remove(eventName);
            }

            EventListener listenerToRemove = null;
            foreach (var listener in listeners)
            {
                if (listener.listeningObject == listeningObject && Delegate.Equals(listener.listeningObject, handler))
                {
                    listenerToRemove = listener;
                    break;
                }
            }
            if (listenerToRemove != null)
            {
                listeners.Remove(listenerToRemove);
            }
        }
    }
}